package com.example.back.mapper;

import com.example.back.entity.Notice;
import com.example.back.entity.otd.NoticeCommentRelation;
import org.apache.ibatis.annotations.*;

import java.io.Serializable;
import java.util.ArrayList;

@Mapper
public interface NoticeMapper {
    @Insert("insert into notice(id,userId,time,text,url,type,triggerUserId,postId,isRead) values(#{id},#{userId},#{time},#{text},#{url},#{type},#{triggerUserId},#{postId},#{isRead})")
    int addNotice(Notice notice);

    @Delete("delete from notice where id= #{id}")
    int deleteNotice(Serializable id);

    @UpdateProvider(type = NoticeMapperProvider.class, method = "getUpdateNoticeSql")
    int updateNotice(Notice notice);

    @Select("select id,userId,time,text,url,type,triggerUserId,postId,isRead from notice where id= #{id}")
    Notice selectNoticeById(Serializable id);

    @SelectProvider(type = NoticeMapperProvider.class, method = "getSelectNoticeSql")
    ArrayList<Notice> selectNotice(Notice notice);

    /**
     * 统计用户的未读通知总数
     */
    @Select("SELECT COUNT(*) FROM notice WHERE userId = #{userId} AND isRead = false")
    int countUnreadNotices(Integer userId);

    /**
     * 统计用户某类通知的未读数量
     */
    @Select("SELECT COUNT(*) FROM notice WHERE userId = #{userId} AND type = #{type} AND isRead = false")
    int countUnreadNoticesByType(@Param("userId") Integer userId, @Param("type") String type);

    /**
     * 标记所有通知为已读
     */
    @Update("UPDATE notice SET isRead = 1 WHERE userId = #{userId}")
    int markAllNoticesAsRead(@Param("userId") Integer userId);

    @Update("update notice set isRead = 1 where id = #{id}")
    int markNoticeAsRead(Serializable id);

    @Select("SELECT n.id AS noticeId, n.text AS noticeText, c.text AS commentText, n.type AS noticeType " +
            "FROM notice n " +
            "LEFT JOIN comment c ON n.postId = c.postId AND n.triggerUserId = c.userId " +
            "WHERE n.id = #{noticeId} AND n.type = 'comment' " +
            "ORDER BY c.id DESC " +
            "LIMIT 1")
    NoticeCommentRelation selectNoticeCommentRelationById(Serializable noticeId);
}
